
//  DetailsScreen.m
//  Gekko
//
//  Created by jose on 02/06/13.
//  Copyright (c) 2013 Jose Luis Lopez. All rights reserved.
//

#import "DetailsScreen.h"

@interface DetailsScreen ()

@end

@implementation DetailsScreen

@synthesize scrollView, labelTitle, labelDate, labelTotal, labelTax1, labelRate1, labelTax2, labelRate2, labelTax3, labelRate3, labelCost, labelDesc, viewContainer, buttonPicture, buttonSave, buttonUpload, buttonPlus, buttonBack, inputDate, inputTotalAmmount, inputTaxAmount1, inputTaxRate1, inputTaxAmount2, inputTaxRate2, inputTaxAmount3, inputTaxRate3, inputCostType, inputDescription, labelPlaceholderDescription;

@synthesize level, comesFromHistory;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    level = 0;
    
    [scrollView setContentSize:CGSizeMake(320, viewContainer.frame.origin.y + buttonUpload.frame.origin.y + buttonUpload.frame.size.height + 20 + 88)];
    
    [labelTitle setText:NSLocalizedString(@"ADD RECEIPT", nil)];
    [labelTitle setFont:[UIFont fontWithName:kFontBold size:26]];
    
    [labelDate setText:NSLocalizedString(@"DATE", nil)];
    [labelDate setFont:[UIFont fontWithName:kFontBold size:16]];
    
    [labelTotal setText:NSLocalizedString(@"TOTAL AMOUNT", nil)];
    [labelTotal setFont:[UIFont fontWithName:kFontBold size:16]];

    [labelTax1 setText:NSLocalizedString(@"TAX AMOUNT", nil)];
    [labelTax1 setFont:[UIFont fontWithName:kFontBold size:16]];

    [labelRate1 setText:NSLocalizedString(@"TAX RATE", nil)];
    [labelRate1 setFont:[UIFont fontWithName:kFontBold size:16]];
    
    [labelTax2 setText:NSLocalizedString(@"TAX AMOUNT", nil)];
    [labelTax2 setFont:[UIFont fontWithName:kFontBold size:16]];
    [labelTax2 setHidden:YES];
    
    [labelRate2 setText:NSLocalizedString(@"TAX RATE", nil)];
    [labelRate2 setFont:[UIFont fontWithName:kFontBold size:16]];
    [labelRate2 setHidden:YES];
    
    [labelTax3 setText:NSLocalizedString(@"TAX AMOUNT", nil)];
    [labelTax3 setFont:[UIFont fontWithName:kFontBold size:16]];
    [labelTax3 setHidden:YES];
    
    [labelRate3 setText:NSLocalizedString(@"TAX RATE", nil)];
    [labelRate3 setFont:[UIFont fontWithName:kFontBold size:16]];
    [labelRate3 setHidden:YES];
    
    [labelCost setText:NSLocalizedString(@"COST TYPE", nil)];
    [labelCost setFont:[UIFont fontWithName:kFontBold size:16]];

    [labelDesc setText:NSLocalizedString(@"DESCRIPTION", nil)];
    [labelDesc setFont:[UIFont fontWithName:kFontBold size:16]];
    
    [buttonSave setTitle:NSLocalizedString(@"SAVE DRAFT", nil) forState:UIControlStateNormal];
    [buttonSave.titleLabel setFont:[UIFont fontWithName:kFontBold size:16]];
    
    [buttonUpload setTitle:NSLocalizedString(@"SAVE & UPLOAD", nil) forState:UIControlStateNormal];
    [buttonUpload.titleLabel setFont:[UIFont fontWithName:kFontBold size:16]];
    
    [labelPlaceholderDescription setText:NSLocalizedString(@"DESCRIPTION PLACEHOLDER", nil)];
    [labelPlaceholderDescription setFont:[UIFont fontWithName:kFontLight size:16]];
    
    [labelDesc setFont:[UIFont fontWithName:kFontBold size:16]];
    
    [inputDate setFont:[UIFont fontWithName:kFontLight size:16]];
    
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.datePickerMode = UIDatePickerModeDate;
    [datePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    inputDate.inputView = datePicker;
    
    UIToolbar *myToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, 320, 44)];
    [myToolbar setTintColor:[UIColor blackColor]];
    UIBarButtonItem *doneButton =
    [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dateDone)];
    [myToolbar setItems:[NSArray arrayWithObject:doneButton] animated:NO];
    inputDate.inputAccessoryView = myToolbar;
    
    [inputTotalAmmount setFont:[UIFont fontWithName:kFontLight size:16]];

    [inputTaxAmount1 setFont:[UIFont fontWithName:kFontLight size:16]];
    
    [inputTaxRate1 setFont:[UIFont fontWithName:kFontLight size:16]];
    
    UIPickerView *taxRatePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    [taxRatePicker setTag:1];
    [taxRatePicker setDelegate:self];
    [taxRatePicker setShowsSelectionIndicator:YES];
    inputTaxRate1.inputView = taxRatePicker;
    
    UIToolbar *taxRateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, 320, 44)];
    [taxRateToolbar setTintColor:[UIColor blackColor]];
    UIBarButtonItem *taxRateDoneButton =
    [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(rateDone)];
    [taxRateToolbar setItems:[NSArray arrayWithObject:taxRateDoneButton] animated:NO];
    inputTaxRate1.inputAccessoryView = taxRateToolbar;
    
    [inputTaxAmount2 setFont:[UIFont fontWithName:kFontLight size:16]];
    [inputTaxAmount2 setHidden:YES];

    [inputTaxRate2 setFont:[UIFont fontWithName:kFontLight size:16]];
    [inputTaxRate2 setHidden:YES];
    
    inputTaxRate2.inputView = taxRatePicker;
    inputTaxRate2.inputAccessoryView = taxRateToolbar;
    
    [inputTaxAmount3 setFont:[UIFont fontWithName:kFontLight size:16]];
    [inputTaxAmount3 setHidden:YES];
    
    [inputTaxRate3 setFont:[UIFont fontWithName:kFontLight size:16]];
    [inputTaxRate3 setHidden:YES];
    
    inputTaxRate3.inputView = taxRatePicker;
    inputTaxRate3.inputAccessoryView = taxRateToolbar;
    
    [inputCostType setFont:[UIFont fontWithName:kFontLight size:16]];

    UIPickerView *costTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    [costTypePicker setTag:2];
    [costTypePicker setDelegate:self];
    [costTypePicker setShowsSelectionIndicator:YES];
    inputCostType.inputView = costTypePicker;
    
    UIToolbar *costTypeToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, 320, 44)];
    [costTypeToolbar setTintColor:[UIColor blackColor]];
    UIBarButtonItem *costTypeDoneButton =
    [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(rateDone)];
    [costTypeToolbar setItems:[NSArray arrayWithObject:costTypeDoneButton] animated:NO];
    inputCostType.inputAccessoryView = costTypeToolbar;
    
    [inputDescription setFont:[UIFont fontWithName:kFontLight size:16]];
 
    [self initWithSharedReceipt];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    tap.numberOfTapsRequired = 1;
    [scrollView addGestureRecognizer:tap];
    
    if (comesFromHistory) {
        NSLog(@"The root is history screen");
        [buttonBack setHidden:NO];
        [buttonBack setUserInteractionEnabled:YES];
    } else
        NSLog(@"The root is not history screen");
}

-(void)initWithSharedReceipt {
    
    [self setDate:[Receipt sharedReceipt].date];
    
    [inputTotalAmmount setText:[Receipt sharedReceipt].totalAmount];
    
    [inputTaxAmount1 setText:[Receipt sharedReceipt].taxAmount1];
    
    [inputTaxRate1 setText:[Receipt sharedReceipt].taxRate1];
    
    [inputTaxAmount2 setText:[Receipt sharedReceipt].taxAmount2];
    
    [inputTaxRate2 setText:[Receipt sharedReceipt].taxRate2];
    
    if ([inputTaxAmount2.text length] > 0 || [inputTaxAmount2.text length] > 0)
        [self plusPressed:buttonPlus];
    
    [inputTaxAmount3 setText:[Receipt sharedReceipt].taxAmount3];
    
    [inputTaxRate3 setText:[Receipt sharedReceipt].taxRate3];
    
    if ([inputTaxAmount3.text length] > 0 || [inputTaxAmount3.text length] > 0)
        [self plusPressed:buttonPlus];
    
    [inputCostType setText:[Receipt sharedReceipt].costType];
    
    [inputDescription setText:[Receipt sharedReceipt].description];
    if ([inputDescription.text length] > 0)
        [labelPlaceholderDescription setHidden:YES];
    

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [buttonPicture setImage:[Receipt sharedReceipt].image forState:UIControlStateNormal];
        [buttonPicture.imageView setContentMode:UIViewContentModeScaleAspectFit];
        [buttonPicture setUserInteractionEnabled:NO];
        [buttonPicture setNeedsDisplay];
    });

    [buttonBack setHidden:YES];
    [buttonBack setUserInteractionEnabled:NO];
    
    if ([[Receipt sharedReceipt].status isEqualToString:kStatusReady] || [[Receipt sharedReceipt].status isEqualToString:kStatusUploaded]) {
        
        [inputDate setUserInteractionEnabled:NO];
        [inputTotalAmmount setUserInteractionEnabled:NO];
        [inputTaxAmount1 setUserInteractionEnabled:NO];
        [inputTaxRate1 setUserInteractionEnabled:NO];
        [inputTaxAmount2 setUserInteractionEnabled:NO];
        [inputTaxRate2 setUserInteractionEnabled:NO];
        [inputTaxAmount3 setUserInteractionEnabled:NO];
        [inputTaxRate3 setUserInteractionEnabled:NO];
        [inputCostType setUserInteractionEnabled:NO];
        [inputDescription setUserInteractionEnabled:NO];
        [buttonPlus setHidden:YES];
        [buttonPlus setUserInteractionEnabled:NO];
        [buttonPicture setUserInteractionEnabled:NO];
        [buttonSave setHidden:YES];
        [buttonSave setUserInteractionEnabled:NO];
        [buttonUpload setHidden:YES];
        [buttonUpload setUserInteractionEnabled:NO];
//        [buttonBack setHidden:NO];
//        [buttonBack setUserInteractionEnabled:YES];
    }
}

- (IBAction)savePressed:(id)sender {
    
    // Saving
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    
        [self saveDataToReceipt];
        [self saveReceipt];
    });
    
    [(UITabBarController*)self.tabBarController setSelectedIndex:0];
    [self.navigationController popToRootViewControllerAnimated:NO];
}

-(void)saveReceipt {
    
    NSLog(@"Saving receipt");
    NSInteger foundedAtIndex = -1;
    for (int i = 0; i < [[ReceiptsHolder sharedReceiptsHolder].arrayReceipts count]; i ++) {
        
        if ([((Receipt *) [[ReceiptsHolder sharedReceiptsHolder].arrayReceipts objectAtIndex:i]).idi
            isEqualToString:[Receipt sharedReceipt].idi]) {
            foundedAtIndex = i;
            break;
        }
    }
    
    if (foundedAtIndex == - 1)
        [[ReceiptsHolder sharedReceiptsHolder].arrayReceipts insertObject:[Receipt sharedReceipt] atIndex:0];
    else
        [[ReceiptsHolder sharedReceiptsHolder].arrayReceipts replaceObjectAtIndex:foundedAtIndex withObject:[Receipt sharedReceipt]];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [ArchiverUnarchiver archiveReceipt:[Receipt sharedReceipt]];
        [Receipt resetSharedReceipt];
    });
    
    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:kKeyShoudReload];
}

- (IBAction)uploadPressed:(UIButton *)sender {
    
    // Saving, checking uploading
    NSString *message = [self validate];
    if ([message length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"VERROR", nil) message:message delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
        [alert show];
    } else {
        
        [Receipt sharedReceipt].status = kStatusUploading;
        [self saveReceipt];
        // Upload receipt
        [[ReceiptController shared] uploadReceipt:[Receipt sharedReceipt]];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"VSUCESS", nil) message:NSLocalizedString(@"VSUCESS MESSAGE", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
        
        [alert show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    // It only comes here when
    [(UITabBarController*)self.tabBarController setSelectedIndex:0];
    [self.navigationController popToRootViewControllerAnimated:NO];
}

-(NSString *)validate {
    
    if ([inputTotalAmmount.text length] == 0)
        return NSLocalizedString(@"ERROR TOTAL AMOUNT", nil);
    else if (([inputTaxAmount1.text length] == 0) && ([inputTaxAmount2.text length] == 0) && ([inputTaxAmount3.text length] == 0))
        return NSLocalizedString(@"ERROR TAX AMOUNT", nil);
    else
        return @"";
}

- (IBAction)plusPressed:(UIButton *)sender {
    
    if (level == 0) {
        
        sender.center = CGPointMake(sender.center.x, sender.center.y + 44);
        viewContainer.center = CGPointMake(viewContainer.center.x, viewContainer.center.y + 44);
        if ([[Receipt sharedReceipt].status isEqualToString:kStatusUploaded] || [[Receipt sharedReceipt].status isEqualToString:kStatusReady]) {
            [sender setHidden:YES];
        }
        [labelTax2 setHidden:NO];
        [labelRate2 setHidden:NO];
        [inputTaxAmount2 setHidden:NO];
        [inputTaxRate2 setHidden:NO];
        scrollView.contentSize = CGSizeMake(320, scrollView.contentSize.height + 44);
        level ++;
    } else if (level == 1) {

        [sender setHidden:YES];
        [labelTax3 setHidden:NO];
        [labelRate3 setHidden:NO];
        [inputTaxAmount3 setHidden:NO];
        [inputTaxRate3 setHidden:NO];
        level ++;
    }
}

- (IBAction)imagePressed:(id)sender {
    
    if (!comesFromHistory)
        [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)backPressed:(UIButton *)sender {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)datePickerValueChanged:(UIDatePicker *)sender {

    [self setDate:sender.date];
}

- (void)setDate:(NSDate *)date {
    
    [Receipt sharedReceipt].date = date;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterLongStyle];
    [inputDate setText:[dateFormatter stringFromDate:date]];
}

-(void)dateDone {
    
    [inputDate resignFirstResponder];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField {

    NSInteger distanceToMove = 0;

    if (textField == inputTaxAmount2 || textField == inputTaxRate2)
        distanceToMove = - 44;
    else if (textField == inputTaxAmount3 || textField == inputTaxRate3)
        distanceToMove = - 88;
    else if (textField == inputCostType) {
        if ([inputTaxAmount2 isHidden])
            distanceToMove = - 44;
        else if ([inputTaxAmount3 isHidden])
            distanceToMove = - 88;
        else
            distanceToMove = - 132;
    }
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.1];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

    self.view.center = CGPointMake(self.view.center.x, self.view.center.y + distanceToMove);

    [UIView commitAnimations];
}


-(void)textFieldDidEndEditing:(UITextField *)textField {
    
    NSInteger distanceToMove = 0;
    
    if (textField == inputTaxAmount2 || textField == inputTaxRate2)
        distanceToMove = 44;
    else if (textField == inputTaxAmount3 || textField == inputTaxRate3)
        distanceToMove = 88;
    else if (textField == inputCostType) {
        if ([inputTaxAmount2 isHidden])
            distanceToMove = 44;
        else if ([inputTaxAmount3 isHidden])
            distanceToMove = 88;
        else
            distanceToMove = 132;
    }
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.1];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    
    self.view.center = CGPointMake(self.view.center.x, self.view.center.y + distanceToMove);
    
    [UIView commitAnimations];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
 
    if (textField == inputTotalAmmount || textField == inputTaxAmount1
        || textField == inputTaxAmount2 || textField == inputTaxAmount3) {
        
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
        
        NSNumber* candidateNumber;
        
        NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        
        range = NSMakeRange(0, [candidateString length]);
        
        [numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];
        
        if (([candidateString length] > 0) && (candidateNumber == nil || range.length < [candidateString length])) {
            
            return NO;
        }
        else
        {
            if([[candidateString componentsSeparatedByString:@","] count] > 1)
                if ([[[candidateString componentsSeparatedByString:@","] objectAtIndex:1] length] > 2) 
                    return NO;
            return YES;
        }
    }
    return YES;
    
}

-(void)textViewDidBeginEditing:(UITextView *)textView {

    [labelPlaceholderDescription setHidden:YES];
    
    NSInteger distanceToMove = 0;

    if ([inputTaxAmount2 isHidden])
        distanceToMove = - 132;
    else if ([inputTaxAmount3 isHidden])
        distanceToMove = - 176;
    else
        distanceToMove = - 220;
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.1];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    
    self.view.center = CGPointMake(self.view.center.x, self.view.center.y + distanceToMove);
    
    [UIView commitAnimations];
}

-(void)textViewDidEndEditing:(UITextView *)textView {
    
    NSInteger distanceToMove = 0;
    
    if ([inputTaxAmount2 isHidden])
        distanceToMove = 132;
    else if ([inputTaxAmount3 isHidden])
        distanceToMove = 176;
    else
        distanceToMove = 220;
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.1];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    
    self.view.center = CGPointMake(self.view.center.x, self.view.center.y + distanceToMove);
    
    [UIView commitAnimations];
}

-(void)keyboardWillBeHidden:(NSNotification *)aNotification {
    
    NSLog(@"Keyboard will hide: saving ...");
    [self saveDataToReceipt];
}

-(void)saveDataToReceipt {
    
    [Receipt sharedReceipt].totalAmount = inputTotalAmmount.text;
    [Receipt sharedReceipt].taxAmount1 = inputTaxAmount1.text;
    [Receipt sharedReceipt].taxRate1 = inputTaxRate1.text;
    [Receipt sharedReceipt].taxAmount2 = inputTaxAmount2.text;
    [Receipt sharedReceipt].taxRate2 = inputTaxRate2.text;
    [Receipt sharedReceipt].taxAmount3 = inputTaxAmount3.text;
    [Receipt sharedReceipt].taxRate3 = inputTaxRate3.text;
    [Receipt sharedReceipt].costType = inputCostType.text;
    [Receipt sharedReceipt].description = inputDescription.text;
}

-(void)hideKeyboard {
    
    NSLog(@"Tapped");
    [inputDate resignFirstResponder];
    [inputTotalAmmount resignFirstResponder];
    [inputTaxAmount1 resignFirstResponder];
    [inputTaxRate1 resignFirstResponder];
    [inputTaxAmount2 resignFirstResponder];
    [inputTaxRate2 resignFirstResponder];
    [inputTaxAmount3 resignFirstResponder];
    [inputTaxRate3 resignFirstResponder];
    [inputCostType resignFirstResponder];
    [inputDescription resignFirstResponder];
}

#pragma mark - Picker View Delegate 

- (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component {

    if (pickerView.tag == 1) {
        
        if ([inputTaxRate1 isFirstResponder])
            [inputTaxRate1 setText:[self pickerView:pickerView titleForRow:row forComponent:component]];
        else if ([inputTaxRate2 isFirstResponder])
            [inputTaxRate2 setText:[self pickerView:pickerView titleForRow:row forComponent:component]];
        else
            [inputTaxRate3 setText:[self pickerView:pickerView titleForRow:row forComponent:component]];
    } else if (pickerView.tag == 2) {
      
        [inputCostType setText:[self pickerView:pickerView titleForRow:row forComponent:component]];
    }
    
}


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    if (pickerView.tag == 1) {
        return 3;
    } else if(pickerView.tag == 2) {
        return 8;
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    if (pickerView.tag == 1) {
        return 1;
    } else if(pickerView.tag == 2) {
        return 1;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {

    if (pickerView.tag == 1) {
        if (row == 0)
            return @"0 %";
        else if(row == 1)
            return @"6 %";
        else
            return @"21 %";
    } else if(pickerView.tag == 2) {
        
        NSString *costs = [NSString stringWithFormat:@"COST %d", row];
        return NSLocalizedString(costs, nil);
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    
    return 300;
}

-(void)rateDone {
    
    [inputTaxRate1 resignFirstResponder];
    [inputTaxRate2 resignFirstResponder];
    [inputTaxRate3 resignFirstResponder];
    [inputCostType resignFirstResponder];
}


@end
